package net.hhk.twitter;

import java.util.ArrayList;
import java.util.List;

import net.hhk.controller.SuggestAdapter;
import net.hhk.controller.SuggestManager;
import net.hhk.data.Constant;
import net.hhk.data.User;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class SearchActivity extends Activity {
	private EditText text;
	private TextWatcher textWatcher;
	private ListView list;
	private String currentSuggestUser = "";
	private int currentPage = 1;
	private View mLoadMoreFooter;
	public LayoutInflater inflater;
	private SuggestManager mgr;
	private SuggestAdapter mAdapter;
	private static final int NUMBER_OF_ITEMS_REQUESTED = 6;
	private static final int MSG_APPEND_MORE_ITEMS = 0;
	private Boolean mLoading = false;
	private int tokenid = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_layout);
		text = (EditText) findViewById(R.id.search);
		text.setInputType(text.getInputType()
				| EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS
				| EditorInfo.TYPE_TEXT_VARIATION_FILTER);

		textWatcher = new TextWatcher() {
			public void afterTextChanged(Editable s) {
				tokenid++;
				loadData(s.toString(), tokenid);
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}
		};
		text.addTextChangedListener(textWatcher);
		text.setSelection(text.getText().length());
		
		LinearLayout write_tweet = (LinearLayout) findViewById(R.id.home_write_tweet);
		write_tweet.setOnClickListener(clickWriteTweet);
		
		Button btn = (Button) findViewById(R.id.btn_tweet);
		btn.setOnClickListener(clickWriteTweet);
		
	

		mgr = new SuggestManager(getApplicationContext());
		inflater = LayoutInflater.from(this);
		mLoadMoreFooter = inflater.inflate(R.layout.profile, null);
		list = (ListView) findViewById(R.id.list);
		// list.setOnScrollListener(mScrollListener);
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// selected item
				User user = (User) parent.getItemAtPosition(position);
				Intent i = new Intent(getApplicationContext(),
						UserProfileActivity.class);
				Bundle b = new Bundle();
				b.putInt("id", user.getUserid());
				i.putExtras(b); // Put your id to your next Inten
				startActivity(i);
				finish();

			}
		});

	}
	
	private OnClickListener clickSearch = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(), SearchActivity.class);

			startActivity(i);

		}
	};


	private OnClickListener clickWriteTweet = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent i = new Intent(getApplicationContext(),
					WriteTweetActivity.class);
			Bundle b = new Bundle();

			b.putInt("isReply", 0);
			i.putExtras(b);
			startActivity(i);

		}
	};

	private void loadData(String suggestName, int _token) {
		final String suggest = suggestName;
		final int token = _token;
		if (!currentSuggestUser.equals(suggest)) {
			list.addFooterView(mLoadMoreFooter);
			currentSuggestUser = suggestName;
			currentPage = 1;
		}

		AsyncTask<String, Void, List<User>> asyncTask = new AsyncTask<String, Void, List<User>>() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPreExecute()
			 */
			@Override
			protected void onPreExecute() {
				super.onPreExecute();

			}

			@Override
			protected List<User> doInBackground(String... params) {
				// Following actions will be done in background
				List<User> result = mgr.getSocialFeed(Constant.GET_SUGGEST, 0,
						1, 6, suggest);
				if (token == tokenid)
					return result;
				else {
					result.clear();
					return result;
				}
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
			 */
			@Override
			protected void onPostExecute(List<User> result) {
				super.onPostExecute(result);

				if (token == tokenid) {
					mAdapter = new SuggestAdapter(SearchActivity.this, result);
					mAdapter.notifyDataSetChanged();
					list.setAdapter(mAdapter);
					if (mAdapter.getCount() < NUMBER_OF_ITEMS_REQUESTED) {
						if (list.getFooterViewsCount() > 0)
							list.removeFooterView(mLoadMoreFooter);
						mLoading = false;
					}
					ListView list = (ListView) findViewById(R.id.list);

					if (result.size() > 0) {
						list.setVisibility(View.VISIBLE);

					} else {
						list.setVisibility(View.GONE);
					}
				}

			}
		};
		asyncTask.execute("Saurabh");
	}

	private void checkLoadMore() {
		if (mLoading)
			return;

		/*
		 * if the loading footer is still there, then we will load more items
		 */
		if (list.getFooterViewsCount() != 0) {
			loadMoreItems();
		}
	}

	private OnScrollListener mScrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// We have nothing to do with this right now
		}

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (view.getLastVisiblePosition() >= 0) {
				if (view.getLastVisiblePosition() >= (totalItemCount - 1)) {
					checkLoadMore();
				}
			}
		}
	};

	private void loadMoreItems() {
		mLoading = true;

		new Thread() {
			public void run() {
				try {
					// in this example, we just simply wait for 2 seconds
					Thread.sleep(2000);
					Message msg = mMainhandler.obtainMessage(
							MSG_APPEND_MORE_ITEMS, generateList());
					mMainhandler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	private Handler mMainhandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_APPEND_MORE_ITEMS:
				ArrayList newData = (ArrayList) msg.obj;
				if (mAdapter == null) {
					mAdapter = new SuggestAdapter(SearchActivity.this, newData);
					list.setAdapter(mAdapter);
				} else {

					mAdapter.appendItems(newData);
				}

				if (newData.size() < NUMBER_OF_ITEMS_REQUESTED) {
					list.removeFooterView(mLoadMoreFooter);
				}
				mLoading = false;
				break;

			}

		}
	};

	private ArrayList generateList() {

		currentPage++;

		return (ArrayList<User>) mgr.getSocialFeed(Constant.GET_SUGGEST, 0,
				currentPage, NUMBER_OF_ITEMS_REQUESTED, currentSuggestUser);
	}

}
